const webpack = require('webpack');
const path = require('path');
const glob = require('glob');
const CleanWebpackPlugin = require('clean-webpack-plugin');         // 清理DIST文件夹
const HtmlWebpackPlugin = require('html-webpack-plugin');           // HTML模板引擎
const MiniCssExtractPlugin = require('mini-css-extract-plugin');    // CSS提取插件
const OptimizeCss = require('optimize-css-assets-webpack-plugin');  // CSS压缩插件
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');          // JS压缩插件
const CopyWebpackPlugin = require('copy-webpack-plugin');           // 文件夹拷贝插件
const final = buildEntriesAndHTML();

const config = {
  entry: final.entries,
  output: {
    filename: '[name].[hash].js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [{
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        'postcss-loader'
      ]
    }, {
      test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
      use: [{
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: assetsPath('img/[name].[hash:6].[ext]'),
          publicPath: '../../'
        }
      }]
    }, {
      test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
      use: [{
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: assetsPath('fonts/[name].[hash:6].[ext]'),
          publicPath: '../../'
        }
      }]
    }, {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: [{
        loader: 'babel-loader',
        options: {
          cacheDirectory: true // 使用缓存
        }
      }, {
        loader: path.resolve('./inject-loader.js') // 开发模式使用注入代码实现html热更新，注入normalize.css
      }]
    }, {
      test: /\.html$/,
      use: [{
        loader: 'html-loader',
        options: {
          interpolate: 'require'
        }
      }],
    }],
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new MiniCssExtractPlugin({
      filename: '[name].[hash].css',
      chunkFilename: '[id].css'
    }),
    new OptimizeCss({
      assetNameRegExp: /\.style\.css$/g,
      cssProcessor: require('cssnano'),
      cssProcessorOptions: {
        discardComments: {
          removeAll: true
        }
      },
      canPrint: true
    }),
    new UglifyJSPlugin(),
    new CopyWebpackPlugin([{
      from: __dirname + '/static',
      to: './static',
      ignore: ['.*']
    }]),
    ...final.htmls
  ],
  optimization: {
    minimizer: [new OptimizeCss({})]
  },
  resolve: {
    extensions: ['.js', '.json', '.jsx', '.css']
  },
  externals: {} // 用来配置require的返回。一般用于加载cdn
}


/**
 * @DO 构建webpack打包入口文件
 * @returns {{entries, htmls: Array}}
 */
function buildEntriesAndHTML() {
  // 用来构建entery
  const result = glob.sync('src/pages/**/*.js');
  const config = {
    hash: true,
    inject: true,
    minify:{
      removeAttributeQuotes: true,  // 是否去除属性引号
      removeEmptyAttributes: true,  // 是否去除空属性
      collapseWhitespace: true      // 是否去除空格
    }
  }
  const entries = {};
  const htmls = [];
  result.forEach(item => {
    const one = path.parse(item);
    const outputfile =  (one.dir).substring('src/'.length) + '/' + one.name;

    entries[outputfile] = './' + item;

    htmls.push(new HtmlWebpackPlugin({
      ...config,
      template: './' + one.dir + '/' + one.name + '.html',
      filename: './' + outputfile + '.html', // 输出html文件的路径
      chunks: [outputfile]
    }));
  });
  return {
    entries,
    htmls
  }
}

/**
 * @DO 构建静态资源路径
 * @param _path
 * @returns {*}
 */
function assetsPath(_path) {
  return path.posix.join('static', _path)
}

module.exports = config;
